<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="商城名称">
                <a-input allow-clear placeholder="请输入商城名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="管理名称">
                <a-input allow-clear placeholder="请输入管理员名称" v-model="queryParam.user_name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="店铺分类">
                <a-select v-model="queryParam.category_id">
                  <a-select-option value="-1"> 全部 </a-select-option>
                  <a-select-option :value="item.id" v-for="item in categoryInfo" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="进件状态">
                <a-select v-model="queryParam.status">
                  <a-select-option value="-1"> 全部 </a-select-option>
                  <a-select-option value="1"> 未进件 </a-select-option>
                  <a-select-option value="2"> 已进件 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="地区选择">
                <city-select v-model="queryParam.area" data-type="area" value-type="1"> </city-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="$refs.table.refresh(1)">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div style="display: flex; justify-content: space-between; margin-bottom: 16px">
        <a-radio-group v-model="queryParam.business_model" @change="$refs.table.refresh(1)">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="1"> 独立运营 </a-radio-button>
          <a-radio-button value="2"> 平台运营 </a-radio-button>
          <a-radio-button value="3"> 当面付 </a-radio-button>
          <a-radio-button value="4"> 扫码点餐 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
          <a-button v-if="!disabled" style="margin-left: 10px" @click="templateSetting">模版店铺设置</a-button>
        </div>
      </div>
      <a-alert
        :message="`当前可创建商城数量：${userInfo.info.username == 'admin' ? '无限制' : canStoreCount}`"
        type="info"
        show-icon
        style="margin-bottom: 16px"
        v-if="canStoreCount > 0"
      />
      <s-table
        style="width: 100%; overflow-x: auto"
        rowKey="id"
        size="default"
        :scroll="{ x: 'max-content' }"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.logo" alt="" />
            </div>
            <div class="info">
              <a-tooltip>
                <template slot="title">
                  {{ record.name }}
                </template>
                <span>{{ record.name }}</span>
              </a-tooltip>

              <span>{{ record.cat_name }}</span>
            </div>
          </div>
        </div>
        <div slot="sass" slot-scope="text, record">
          <!-- <div class="name" v-if="record.admin_saas_user">
            <div class="pic">
              <img :src="record.admin_saas_user.avatar" alt="" />
              <a-avatar shape="square" :size="64" icon="user" />
            </div>
            <div class="info">
              <span>{{ record.admin_saas_user.name }}</span>
              <span>{{ record.admin_saas_user.mobile }}</span>
            </div>
          </div> -->
          <a-popover title="管理员信息" v-if="record.admin_saas_user">
            <template slot="content">
              <div v-if="record.admin_name">姓名：{{ record.admin_name }}</div>
              <div v-if="record.admin_user_name">登录账户：{{ record.admin_user_name }}</div>
              <div v-if="record.admin_saas_user.mobile">手机号码：{{ record.admin_saas_user.mobile }}</div>
            </template>

            <span> {{ record.admin_saas_user.name }}</span>
          </a-popover>
          <span v-else>暂无信息</span>
        </div>
        <span slot="agent_admin_name" slot-scope="text, scope">{{
          scope.agent_admin ? scope.agent_admin.name : '-'
        }}</span>
        <span slot="salesman_admin_name" slot-scope="text, scope">{{
          scope.salesman_admin ? scope.salesman_admin.name : '-'
        }}</span>
        <span slot="created_at" slot-scope="text">{{ text | timeFormat }}</span>
        <span slot="admin" v-if="isSuperAdmin" slot-scope="text, record">
          {{ record.username || '' }}
          <!-- {{ admin.username ? admin.username : '-' }} -->
          <!-- <a-tag color="blue" v-if="admin.name">{{ admin.name }}</a-tag> -->
        </span>
        <div slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope == 0 ? 'disabled' : 'open'"></span>
            <span>{{ scope == 0 ? '未开启' : '已开启' }}</span>
          </div>
        </div>
        <span slot="is_join" slot-scope="isJoin, record">
          <!-- <a-tag color="blue" v-if="isJoin == 1">
            已加入
          </a-tag>
          <a-tag color="orange" v-if="isJoin == 2">
            审核中
          </a-tag>
          <a-tag color="red" v-if="isJoin == 0">
            未加入
          </a-tag> -->
          <a-switch :defaultChecked="isJoin" @change="onJoinUnionStatus(record)" />
        </span>
        <span slot="business_model" slot-scope="text">
          <a-tag color="blue">
            {{ text == 1 ? '独立运营' : text == 2 ? '平台运营' : text == 3 ? '当面付' : text == 4 ? '点餐' : '' }}
          </a-tag>
        </span>
        <span slot="self_mini" slot-scope="text">
          {{ text == 1 ? '是' : '否' }}
        </span>
        <span slot="action" slot-scope="text, record" v-if="!disabled">
          <div>
            <a-button type="link" @click="onInStore(record)" size="small">进入</a-button>
            <a-divider type="vertical" style="margin: 0 1px" />
            <a-button type="link" @click="onCopyLink(record)" size="small">复制链接</a-button>
          </div>
          <div>
            <a-button type="link" @click="onSetting(record)" size="small">设置</a-button>
            <template v-if="isSuperAdmin && record.id != '1'">
              <a-divider type="vertical" style="margin: 0 1px" />
              <a-popconfirm title="确认删除商城吗？" @confirm="handleDelete(record)">
                <a-button type="link" size="small">删除</a-button>
              </a-popconfirm>
            </template>
          </div>
          <!-- <a-dropdown>
            <a-button type="link" size="small"> 更多 <a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-button type="link" @click="onCopyLink(record)" size="small">复制链接</a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="link" @click="onSetting(record)" size="small">设置</a-button>
              </a-menu-item>
              <a-menu-item v-if="isSuperAdmin">
                <a-popconfirm title="确认删除商城吗？" :disabled="record.id == 1" @confirm="handleDelete(record)">
                  <a-button type="link" :disabled="record.id == 1" size="small">删除</a-button>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown> -->

          <!-- <a-button type="link" @click="onOrderList(record)" size="small">续费记录</a-button> -->
          <!-- <a-button
            type="link"
            @click="createBusiness(record)"
            size="small"
            v-if="
              (!record.cloud_is_delete && !record.is_cloud_store) ||
              (record.cloud_is_delete == 1 && record.is_cloud_store)
            "
            >开通云仓</a-button
          > -->
        </span>
      </s-table>
    </a-card>
    <a-modal title="缴费记录" v-model="reOrder" :width="800">
      <a-table :columns="reOrderColumns" :data-source="reOrderData">
        <a slot="name" slot-scope="text">{{ text }}</a>
      </a-table>
    </a-modal>
    <a-modal title="添加商城" v-model="visible" :confirm-loading="confirmLoading" @ok="handleOk">
      <a-form-model-item label="商城LOGO" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <cyyUploadImg
          @uploadSuccess="
            (e) => {
              logo = e.data
            }
          "
          @deleteImg="logo = ''"
          :imgSrc="logo"
        >
        </cyyUploadImg>
      </a-form-model-item>
      <a-form-model-item label="商城名称" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-input v-model="storeName" placeholder="请输入商城名称" />
      </a-form-model-item>
      <a-form-model-item label="账户名称" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-input v-model="username" placeholder="请输入账户名称" />
      </a-form-model-item>
      <a-form-model-item label="商城密码" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-input v-model="password" placeholder="请输入商城密码" />
      </a-form-model-item>
      <a-form-model-item label="地区" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <Address v-model="area"></Address>
      </a-form-model-item>
      <a-form-model-item label="管理员用户" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <div style="display: flex">
          <a-input v-model="saas_user_name" placeholder="请选择用户" disabled></a-input>
          <a-button type="primary" style="margin-left: 12px" @click="visibleUser = true">选择</a-button>
        </div>
      </a-form-model-item>
      <a-form-model-item label="运营模式" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        独立小程序
      </a-form-model-item>
    </a-modal>
    <!-- 选择用户弹窗 -->
    <a-modal title="选择用户" style="width: 300px" v-model="visibleUser" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search placeholder="输入昵称搜索" v-model="keyword" allowClear enter-button @search="search" />
      </div>
      <s-table ref="table1" rowKey="id" :columns="userColumns" :data="loadUserData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record)"> 选择 </a-button>
        </span>
        <span slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope.is_disable == 0 ? 'open' : 'close'"></span>
            <span>{{ scope.is_disable == 0 ? '已启用' : '已禁用' }}</span>
          </div>
        </span>
      </s-table>
    </a-modal>
    <!-- <a-modal
      width="650px"
      :maskClosable="false"
      :title="settingStoreTitle"
      v-model="visibleSetting"
      :confirm-loading="confirmLoading"
      @cancel="onStoreSettingCancel"
      :footer="null"
    >
      <a-tabs v-model="storeSetingTab">
        <a-tab-pane key="share" tab="联盟用户分销设置">
          <ShareSetting :storeId="currentStore.id" v-if="currentStore"></ShareSetting>
        </a-tab-pane>
        <a-tab-pane key="2" tab="推荐人设置">
          <ReferralSetting :storeId="currentStore.id" v-if="currentStore"></ReferralSetting>
        </a-tab-pane>
        <a-tab-pane key="3" tab="让利设置">
          <TransferProfitSetting :storeId="currentStore.id" v-if="currentStore"></TransferProfitSetting>
        </a-tab-pane>
        <a-tab-pane key="4" tab="其他设置">
          <OtherSetting :isSuperAdmin="isSuperAdmin" :storeId="currentStore.id" v-if="currentStore"></OtherSetting>
        </a-tab-pane>
        <a-tab-pane key="5" tab="费用设置">
          <PriceSetting :isSuperAdmin="isSuperAdmin" :storeId="currentStore.id" v-if="currentStore"></PriceSetting>
        </a-tab-pane>
        <a-tab-pane key="6" tab="修改密码">
          <EditPass :storeId="currentStore.id" v-if="currentStore"></EditPass>
        </a-tab-pane>
      </a-tabs>
    </a-modal> -->
    <!-- 创建商户弹窗 -->
    <!-- <a-modal
      title="创建商户"
      width="800px"
      v-model="showCreated"
      @ok="editBusiness"
      :afterClose="() => closeModal('businessForm')"
      :destroyOnClose="true"
    >
      <a-form-model
        ref="businessForm"
        :model="businessForm"
        :rules="businessRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="商户logo" prop="logo">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                businessForm.logo = e.data
              }
            "
            @deleteImg="businessForm.logo = ''"
            :imgSrc="businessForm.logo"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <a-form-model-item label="商户名称" prop="name">
          <a-input v-model="businessForm.name" placeholder="请输入商户名称" />
          <p class="tip">商户名称长度为4~30个字符，一个中文等于2个字符。</p>
        </a-form-model-item>
        <a-form-model-item label="商户密码" prop="password">
          <a-input v-model="businessForm.password" placeholder="请输入商户密码" />
        </a-form-model-item>
        <a-form-model-item label="商户电话" prop="tel">
          <a-input v-model="businessForm.tel" placeholder="请输入商户电话" />
        </a-form-model-item>
        <a-form-model-item label="商户类型" prop="type">
          <a-select v-model="businessForm.type" placeholder="请选择商户类型">
            <a-select-option value="0"> 个人 </a-select-option>
            <a-select-option value="1"> 企业 </a-select-option>
            <a-select-option value="2"> 个体工商户 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="资料证书" prop="certificate">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                businessForm.certificate = e.data
              }
            "
            @deleteImg="businessForm.certificate = ''"
            :imgSrc="businessForm.certificate"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <a-form-model-item label="身份证正面" prop="id_card_front">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                businessForm.id_card_front = e.data
              }
            "
            @deleteImg="businessForm.id_card_front = ''"
            :imgSrc="businessForm.id_card_front"
            imgSizeText="750*320"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <a-form-model-item label="身份证反面" prop="id_card_reverse">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                businessForm.id_card_reverse = e.data
              }
            "
            @deleteImg="businessForm.id_card_reverse = ''"
            :imgSrc="businessForm.id_card_reverse"
            imgSizeText="750*320"
          >
          </cyyUploadImg>
        </a-form-model-item>
      </a-form-model>
    </a-modal> -->

    <a-modal width="700px" v-model="visibleTemplate" title="新建模版" ok-text="确认" cancel-text="取消" @ok="onSubmit">
      <a-form-model
        ref="templateRuleForm"
        :model="templateForm"
        :rules="templateRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="选择默认模版" prop="id">
          <a-select v-model="templateForm.id" allowClear :filter-option="filterOption" show-search>
            <a-select-option :value="item.id" v-for="item in storeList" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="默认类型" prop="type" help="店铺开店后，使用默认模版作为开店后的店铺模板">
          <a-checkbox-group v-model="templateForm.type">
            <a-checkbox value="home"> 商城首页 </a-checkbox>
            <a-checkbox value="category"> 商品分类 </a-checkbox>
            <a-checkbox value="product"> 商城商品 </a-checkbox>
            <a-checkbox value="center"> 个人中心 </a-checkbox>
            <a-checkbox value="footnav"> 底部菜单 </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { Address, STable } from '@/components'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getList, addStore, delStore, storeReOrder, changeJoinUnionStatus, getCategoryInfo } from '@/api/store'
import { generateTokenBySaas } from '@/api/auth'
import ShareSetting from './setting/Share'
import { cyyUploadImg } from '@/components/CyyUi'
import ReferralSetting from './setting/Referral'
import TransferProfitSetting from './setting/TransferProfit'
import EditPass from './setting/EditPass'
import OtherSetting from './setting/Other'
import { creatBusiness } from '@/api/purchase/purchase'
import PriceSetting from './setting/PriceSetting'
import { templateDefaultInfo, templateDefaultSave } from '@/api/saas/copy'
import { wechatMpCardList } from '@/api/wechartVipCard'
import { getSelectUserList } from '@/api/user'
import CitySelect from '@/components/CitySelect/CitySelect'

const reOrderColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    scopedSlots: { customRender: 'id' },
  },
  {
    title: '备注',
    dataIndex: 'desc',
    key: 'desc',
    ellipsis: true,
    width: '25%',
  },
  {
    title: '订单号',
    dataIndex: 'order_no',
    key: 'order_no',
    ellipsis: true,
    width: '30%',
  },
  {
    title: '支付时间',
    dataIndex: 'pay_time',
    key: 'pay_time',
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'is_pay',
    key: 'is_pay',
    ellipsis: true,
  },
]

export default {
  name: 'SaasStoreList',
  components: {
    Address,
    STable,
    ShareSetting,
    ReferralSetting,
    TransferProfitSetting,
    OtherSetting,
    PriceSetting,
    EditPass,
    cyyUploadImg,
    CitySelect,
  },
  data() {
    let checkPic = (rule, value, callback) => {
      if (!value) {
        if (rule.field == 'logo') {
          callback(new Error('请上传商户logo'))
        }
        if (rule.field == 'certificate') {
          callback(new Error('请上传资料证书'))
        }
        if (rule.field == 'id_card_front') {
          callback(new Error('请上传身份证正面'))
        }
        if (rule.field == 'id_card_reverse') {
          callback(new Error('请上传身份证反面'))
        }
      } else {
        callback()
      }
    }
    return {
      advanced: false,
      isSuperAdmin: false,
      visible: false,
      confirmLoading: false,
      storeName: '',
      columns: [],
      canStoreCount: 0,
      loadData: (parameter) => {
        let data = JSON.parse(JSON.stringify(this.queryParam))
        if (data.area.length) {
          let [province_id, city_id, district_id] = data.area
          data.province_id = province_id
          data.city_id = city_id
          data.district_id = district_id
        }

        delete data.area
        return getList({ ...parameter, ...data })
          .then((res) => {
            this.canStoreCount = res.data.canStoreCount
            this.isSuperAdmin = res.data.is_super_admin
            if (!res.data.is_super_admin && this.columns.find((el) => el.title === '管理员')) {
              this.columns.splice(2, 1)
            }
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },
      settingStoreTitle: '商城设置',
      visibleSetting: false,
      currentStore: null,
      storeSetingTab: 'share',
      reOrderColumns,
      reOrderData: [],
      reOrder: false,
      // 显示创建云仓商户弹窗
      showCreated: false,
      // 新增 编辑商户的表单
      businessForm: {
        logo: '',
        name: '',
        password: '',
        tel: '',
        type: '',
        certificate: '',
        id_card_reverse: '',
        id_card_front: '',
      },
      businessRules: {
        name: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入供货商电话号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入供货商密码', trigger: 'blur' }],
        type: [{ required: true, message: '请选择供货商类型', trigger: 'blur' }],
        logo: [{ required: true, validator: checkPic, trigger: 'change' }],
        certificate: [{ required: true, validator: checkPic, trigger: 'change' }],
        id_card_front: [{ required: true, validator: checkPic, trigger: 'change' }],
        id_card_reverse: [{ required: true, validator: checkPic, trigger: 'change' }],
      },
      currentBusiness: {},
      showCreated: false,
      btnLoading: false,
      password: '',
      username: '',
      area: {},
      logo: '',
      queryParam: {
        name: '',
        id: '',
        user_name: '',
        category_id: '-1',
        status: '-1',
        business_model: '-1',
        area: [],
      },
      // 商城分类列表
      categoryInfo: [],
      selectedRowKeys: [],
      visibleTemplate: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      templateForm: {
        type: '',
        id: '',
      },
      templateRules: {
        id: [{ required: true, message: '模版不能为空', trigger: 'change' }],
        type: [{ required: true, message: '模版类型不能为空', trigger: 'change' }],
      },
      storeList: [],

      userColumns: [
        {
          title: 'ID',
          dataIndex: 'id',
        },
        {
          title: '用户信息',
          scopedSlots: { customRender: 'baseinfo' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
        },
      ],

      loadUserData: (parameter) => {
        if (this.requiredKeyword && this.keyword === '') {
          return new Promise((resolve, reject) => {
            resolve({
              data: [],
              pageNo: 1,
              totalCount: 0,
            })
          })
        }

        return getSelectUserList({
          ...parameter,
          type: 'user',
          keyword: this.keyword,
        }).then((res) => {
          return res.data
        })
      },
      keyword: '',
      visibleUser: false,
      saas_user_name: '',
      saas_user_id: '',
      disabled: false,
      requiredKeyword: false,
    }
  },
  methods: {
    async templateSetting() {
      const hide = this.$message.loading('加载中', 0)
      const res = await templateDefaultInfo()
      hide()
      if (!res.code) {
        this.visibleTemplate = true
        if (!res.default) {
          this.templateForm = {
            id: '',
            type: '',
          }
        } else {
          let { store_id: id, type } = res.default

          this.templateForm = {
            id,
            type,
          }

          if (type.includes('all')) {
            this.templateForm.type = ['home', 'category', 'product', 'center', 'footnav']
          }
        }

        return
      }

      this.$message.error(res.msg)
    },

    onSubmit() {
      this.$refs.templateRuleForm.validate(async (valid) => {
        if (valid) {
          const hide = this.$message.loading('请求中', 0)
          let templateForm = JSON.parse(JSON.stringify(this.templateForm))
          if (templateForm.type.length === 4) {
            templateForm.type = ['all']
          }

          const res = await templateDefaultSave(templateForm)
          hide()
          if (res.code == 0) {
            this.$message.success('设置成功～')
            this.visibleTemplate = false
            return
          }
          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    handleSearch(value) {
      let [item] = this.storeList.filter((d, index) => {
        return d.id == value
      })
      this.form.id = item.id
    },
    onJoinUnionStatus: function (item) {
      changeJoinUnionStatus({ id: item.id, status: item.is_alliance ? 0 : 1 }).then((res) => {
        if (res.code == 0) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onOrderList: function (item) {
      storeReOrder({ store_id: item.id }).then((res) => {
        if (res.code === 0) {
          this.reOrder = true
          this.reOrderData = res.list
        }
      })
    },
    onCopyLink: function (item) {
      const host = window.location.protocol + '//' + window.location.host
      this.$copyText(host + '/h5/#/?store_id=' + item.id)
        .then((message) => {
          this.$message.success('复制成功')
        })
        .catch((err) => {
          console.log('copy.err', err)
          this.$message.error('复制失败')
        })
    },
    onAdd: function () {
      this.visible = true
    },
    onInStore: function (item) {
      generateTokenBySaas({ storeId: item.id, username: item.username })
        .then((res) => {
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.set('isSaas', res.data.is_saas)
            storage.set('isSaasStore', true)
            storage.set('storeId', item.id)
            storage.remove('isPlatform')
            storage.remove('isSupplier')
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {})
    },
    onSetting: function (item) {
      this.$router.push({ path: '/saas/store/setting?id=' + item.id })
      // this.currentStore = null
      // this.$nextTick(() => {
      //   this.currentStore = item
      // })
      // this.settingStoreTitle = '商城设置 - ' + item.store_name + '(ID:' + item.id + ')'
      // this.visibleSetting = true
    },
    onStoreSettingCancel: function () {
      setTimeout(() => {
        this.storeSetingTab = 'share'
      }, 500)
    },
    handleDelete: function (item) {
      this.$message.loading({ content: '处理中...', key: 'deleteLoading' })
      delStore({ store_id: item.id }).then((res) => {
        if (res.code == 0) {
          this.$refs.table.refresh(true)
          this.$message.success({ content: res.msg, key: 'deleteLoading' })
        } else {
          this.$message.warning({ content: res.msg, key: 'deleteLoading' })
        }
      })
    },
    handleOk: function () {
      if (this.logo == '') {
        this.$message.warning('请上传商城LOGO')
        return
      }

      if (this.storeName == '') {
        this.$message.warning('请输入商城名称')
        return
      }

      if (this.username == '') {
        this.$message.warning('请输入账户名称')
        return
      }

      if (this.password == '') {
        this.$message.warning('请输入商城密码')
        return
      }

      // 取消强制添加手机管理员功能
      // if (this.saas_user_id == '') {
      //   this.$message.warning('请选择手机管理员')
      //   return
      // }

      this.confirmLoading = true
      const { password, username, storeName: name, area, saas_user_id, logo } = this
      addStore({
        name,
        password,
        area,
        username,
        saas_user_id,
        logo,
      })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.visible = false
            this.$refs.table.refresh(true)
            this.password = ''
            this.saas_user_id = ''
            this.username = ''
            this.storeName = ''
            this.area = {}
            this.saas_user_id = ''
            this.logo = ''
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {
          this.confirmLoading = false
        })
    },
    // 点击创建云仓商户
    // createBusiness(record) {
    //   this.currentBusiness = record
    //   this.showCreated = true
    // },
    // 点击创建商户
    editBusiness() {
      this.$refs['businessForm'].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          this.businessForm.user_id = this.currentBusiness.id
          const res = await creatBusiness(this.businessForm)
          this.btnLoading = false
          if (res.code == 0) {
            this.showCreated = false
            this.$refs.table.refresh()
            this.$message.success('创建成功')
            return
          }
          this.$message.error(res.msg)
        } else {
          return false
        }
      })
    },
    closeModal(e) {
      this.$refs[e].resetFields()
    },
    // 获取全部商城分类
    getCategoryInfo() {
      getCategoryInfo({}).then((res) => {
        if (res.code == 0) {
          this.categoryInfo = res.data
        }
      })
    },

    // 选择用户
    onSelect(item) {
      this.saas_user_name = item.name
      this.saas_user_id = item.id
      this.visibleUser = false
    },

    search() {
      if (this.requiredKeyword && this.keyword === '') return this.$message.error('昵称不能为空')
      this.$refs.table1.refresh(true)
    },
  },
  async mounted() {
    let columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        width: 80,
      },
      {
        title: '店铺信息',
        scopedSlots: {
          customRender: 'name',
        },
      },
      {
        title: '运营模式',
        dataIndex: 'business_model',
        scopedSlots: {
          customRender: 'business_model',
        },
        width: 150,
      },
      {
        title: '店铺管理员',
        width: 150,
        scopedSlots: {
          customRender: 'sass',
        },
        ellipsis: true,
      },
      // {
      //   title: '联盟券数额',
      //   width: 200,
      //   scopedSlots: {
      //     customRender: 'league_price',
      //   },
      // },
      // {
      //   title: '管理员',
      //   dataIndex: 'admin',
      //   scopedSlots: {
      //     customRender: 'admin',
      //   },
      // },
      // {
      //   title: '是否加入联盟',
      //   dataIndex: 'is_alliance',
      //   scopedSlots: {
      //     customRender: 'is_join',
      //   },
      // },
      {
        title: '店主手机',
        dataIndex: 'contact_tel',
        width: 150,
      },
      {
        title: '店铺代理',
        scopedSlots: {
          customRender: 'agent_admin_name',
        },
      },
      {
        title: '店铺业务员',
        scopedSlots: {
          customRender: 'salesman_admin_name',
        },
      },
      {
        title: '进件状态',
        dataIndex: 'wechat_audit_text',
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        scopedSlots: {
          customRender: 'created_at',
        },
        sorter: (a, b) => {
          a.created_at - b.created_at
        },
      },
      {
        title: '操作',
        width: 160,
        dataIndex: 'action',
        fixed: 'right',
        scopedSlots: {
          customRender: 'action',
        },
      },
    ]

    if (storage.get('isDandianpu')) {
      columns.splice(2, 1)

      columns.splice(3, 1, {
        title: '独立小程序',
        dataIndex: 'self_mini',
        scopedSlots: {
          customRender: 'self_mini',
        },
        width: 150,
      })
    }

    if (this.userInfo.info.type !== 'admin' && this.userInfo.info.type !== 'saas_staff') {
      this.disabled = true

      if (this.userInfo.info.type === 'bd_agent') {
        columns.splice(columns.length - 1, 1)
      }
    }

    if (this.userInfo.info.username !== 'admin') {
      this.requiredKeyword = true
    }

    this.columns = columns
    this.getCategoryInfo()
    this.$refs.table.refresh(1)

    const res = await wechatMpCardList({})
    if (!res.code) {
      this.storeList = res.store_list || []
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user
    },
  },
}
</script>

<style scoped lang="less">
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    margin-right: 15px;
    width: 100px;

    span {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .close {
    background-color: #ff4400;
  }
  .disabled {
    background-color: #ccc;
  }
  .open {
    background-color: #65c817;
  }
}

::v-deep {
  .ant-cascader-picker,
  .ant-cascader-input {
    height: 32px;
  }
}
</style>
